<?php

namespace app\admin\controller;

use app\service\LogService;
use think\exception\ValidateException;

class Log extends Admin
{

    public function __construct(LogService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "日志列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["user_name"])) {
            $where[] = ['user_name', 'like', "%{$params['user_name']}%"];
        }
        if (!empty($params["url"])) {
            $where[] = ['url', 'like', "%{$params['url']}%"];
        }
        if (!empty($params["module"])) {
            $where[] = ['module', '=', $params['module']];
        }
        if (!empty($params["user_id"])) {
            $where[] = ['user_id', '=', $params['user_id']];
        }
        if (!empty($params["ip"])) {
            $where[] = ['ip', '=', $params['ip']];
        }
        if (!empty($params["create_at"])) {
            $between = explode(" - ", $params["create_at"]);
            if (count($between) == 2) {
                $where[] = ['create_at', '>=', $between[0]];
                $where[] = ['create_at', '<=', $between[1]];
            }
        }
        $ret = $this->service->getList($where);
        $this->result($ret);
    }

    public function remove()
    {
        $id = $this->request->post("id");
        if (empty($id)) {
            throw new ValidateException("传参错误");
        }
        $ids = str2arr($id);
        $this->service->delete(["id" => $ids]);
        $this->success("清理成功");
    }

    public function clear()
    {
        $this->service->clear();
        $this->success("清理成功");
    }
}
